package cn.bs.controller;

import cn.bs.domain.dao.Orders;
import cn.bs.domain.dao.Seat;
import cn.bs.domain.pojo.Result;
import cn.bs.mapper.OrderMapper;
import cn.bs.mapper.SeatMapper;
import cn.bs.utils.PayUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import jakarta.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Controller
@RequestMapping("/alipay")
public class AliPayController {
    @Autowired
    private PayUtil payUtil;
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private SeatMapper seatMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private Orders orderModels = null;
//    private Integer userId = null;

    @ResponseBody
    @PostMapping("/pay")
    public String alipay(HttpServletRequest request, @RequestParam String orderId) throws AlipayApiException {
//        orderModels = orderModel;
//        tokens = token;
        Integer userId = Integer.valueOf(stringRedisTemplate
                .opsForValue().get(request.getHeader("Authorization")));
//        this.userId = userId;
        if (userId == null){
            return "用户未登录";
        }

        System.out.println("userId :" + userId);
        Orders order = orderMapper.getById(Integer.valueOf(orderId));

        System.out.println("orderUserId :" + order.getUserId());
        if (order == null){
            return "订单不存在";
        }

        if (!Objects.equals(order.getUserId(), userId)){
            return "该订单不属于您，无需支付";
        }

        if (order.getStatus() == 1){
            return "该订单已支付";
        }else if (order.getStatus() == 2){
            return "该订单已取消";
        }
        Seat seat = seatMapper.getById(order.getSeatId());
        if (seat.getStatus() == 1){
            return "该座位已被预定，请选择其它位置";
        }
        //生成订单号（支付宝的要求？）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-", "").toUpperCase();
//        Orders order = orderService.getById(Integer.valueOf(orderId));
        if (order == null) {
            throw new IllegalArgumentException("订单不存在");
        }
        this.orderModels = order;
        userId = order.getUserId();
//        String OrderNum = time + user;
        String OrderNum = time + order.getId();
        float oderValue = order.getOrderAmount().floatValue();
//        System.out.println("商品名字是" + orderModel.getUserId().getIdleName());
        //调用封装好的方法（给支付宝接口发送请求）
        return payUtil.sendRequestToAlipay(OrderNum, oderValue, "预定座位");

    }

    //    当我们支付完成之后跳转这个请求并携带参数，我们将里面的订单id接收到，通过订单id查询订单信息，信息包括支付是否成功等
    @GetMapping("/toSuccess")
    public String returns(String out_trade_no) throws ParseException {
        String query = payUtil.query(out_trade_no);
        System.out.println("==>" + query);
        JSONObject jsonObject = JSONObject.parseObject(query);
        Object o = jsonObject.get("alipay_trade_query_response");
        Map map = (Map) o;
        System.out.println(map);
        Object s = map.get("trade_status");
        if (s.equals("TRADE_SUCCESS")) {
            //当支付成功之后要执行的操作
            System.out.println("订单支付成功");
//            Long userId = jwtHelper.getUserId(tokens);
//            orderModels.setUserId(userId);
            orderModels.setStatus(1);
            orderModels.setPayDate(new Date());
            orderModels.setPayAmount(orderModels.getOrderAmount());
            orderMapper.updateById(orderModels);
            Seat seat = seatMapper.getById(orderModels.getSeatId());
            seat.setStatus(1);
            seatMapper.updateById(seat);
            Integer canteenId = orderModels.getCanteenId();

            System.out.println(s);
            return "redirect:http://localhost:8082/canteenInfo/" + canteenId;
        } else {
//            支付失败要执行的操作
            System.out.println("订单支付失败");
            return "index";
        }
    }

    /*
参数1：订单号
参数2：订单金额
参数3：订单名称
 */

}